package com.example.himalaya.view.activity;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;

import com.example.himalaya.R;
import com.example.himalaya.view.adapters.PlayerTrackPagerAdapter;
import com.example.himalaya.base.BaseActivity;
import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.view.callback.IPlayerViewCallback;
import com.example.himalaya.view.callback.ISobPopViewCallback;
import com.example.himalaya.view.callback.ILoveSongViewCallback;
import com.example.himalaya.presenters.LoveSongPresenter;
import com.example.himalaya.presenters.PlayerPresenter;
import com.example.himalaya.constants.Constants;
import com.example.himalaya.utils.ImageBlur;
import com.example.himalaya.utils.LogUtil;
import com.example.himalaya.view_component.PlayMusicView;
import com.example.himalaya.view_component.SobPopWindow;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PlayerViewActivity extends BaseActivity implements IPlayerViewCallback, ISobPopViewCallback, ILoveSongViewCallback {

    // Constant
    private static final String TAG = "PlayerViewActivity";

    // Format Tool
    @SuppressLint("SimpleDateFormat")
    private SimpleDateFormat mMinFormat = new SimpleDateFormat("mm:ss");
    @SuppressLint("SimpleDateFormat")
    private SimpleDateFormat mHourFormat = new SimpleDateFormat("hh:mm:ss");

    // UI object
    private ImageView mControlBtn;
    private TextView mTotalDuration;
    private TextView mCurrentPosition;
    private SeekBar mDurationBar;
    private ImageView mPlayNextBtn;
    private ImageView mPlayPreBtn;
    private TextView mTrackTitle;
    private String mTrackTitleText;
    private ViewPager mTrackPageView;
    private PlayerTrackPagerAdapter mTrackPagerAdapter;
    private ImageView mPlayModeSwitchBtn;
    private ImageView mPlayListBtn;
    private ImageView mPlayerBackgroundImg;
    private Context mContext;
    private ImageView mLoveBtn;
    private ImageView mDownloadBtn;


    // Other UI Object
    private PlayMusicView mPlayMusicView;
    private SobPopWindow mSobPopWindow;


    // Logic Object
    private PlayerPresenter mPlayerPresenter;
    private LoveSongPresenter mLoveSongPresenter;

    // Animator object
    private ValueAnimator mEnterBgAnimator;
    private ValueAnimator mOutBgAnimator;

    // Map
    public static Map<XmPlayListControl.PlayMode, XmPlayListControl.PlayMode> sPlayModeRule = new HashMap<>();
    public static XmPlayListControl.PlayMode mCurrentMode = XmPlayListControl.PlayMode.PLAY_MODEL_LIST;
    private int mCurrentProgress = 0;

    // Flag
    private boolean mIsUserTouchProgressBar = false;
    private boolean mIsUserSlidePager = false;


    static {
        //设置播放器模式，mode取值为PlayMode中的下列之一：
        //PLAY_MODEL_SINGLE     单曲播放
        //PLAY_MODEL_SINGLE_LOOP 单曲循环播放
        //PLAY_MODEL_LIST       列表播放
        //PLAY_MODEL_LIST_LOOP  列表循环
        //PLAY_MODEL_RANDOM     随机播放
        sPlayModeRule.put(XmPlayListControl.PlayMode.PLAY_MODEL_LIST, XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP);
        sPlayModeRule.put(XmPlayListControl.PlayMode.PLAY_MODEL_LIST_LOOP, XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM);
        sPlayModeRule.put(XmPlayListControl.PlayMode.PLAY_MODEL_RANDOM, XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP);
        sPlayModeRule.put(XmPlayListControl.PlayMode.PLAY_MODEL_SINGLE_LOOP, XmPlayListControl.PlayMode.PLAY_MODEL_LIST);
    }

    private Track mCurrentTrack;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_player);

        mContext = getBaseContext();


        initVariable();


        initBgAnimation();

        initPresenter();

        initView();

        initListener();
    }

    private void initPresenter() {
        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mLoveSongPresenter = LoveSongPresenter.getInstance();


        // 注册回调
        mPlayerPresenter.registerViewCallback(this);
        mLoveSongPresenter.registerViewCallback(this);
    }

    private void initVariable() {
        mContext = BaseApplication.getAppContext();

        // get element
        mControlBtn = this.findViewById(R.id.play_or_pause_btn);                // 播放键
        mTotalDuration = this.findViewById(R.id.track_duration);                // 歌曲总时长
        mCurrentPosition = this.findViewById(R.id.current_position);            // 当前播放出
        mDurationBar = this.findViewById(R.id.track_seek_bar);                  // 时长进度条
        mPlayNextBtn = this.findViewById(R.id.play_next);                       // 下一首按钮
        mPlayPreBtn = this.findViewById(R.id.play_pre);                         // 上一首按钮
        mTrackTitle = this.findViewById(R.id.track_title);                      // 歌名
        mTrackPageView = this.findViewById(R.id.track_pager_view);              // 歌曲封面
        mPlayModeSwitchBtn = this.findViewById(R.id.play_mode_switch_btn);      // 播放模式
        mPlayListBtn = this.findViewById(R.id.main_player_list);                // 播放列表

        mPlayerBackgroundImg = this.findViewById(R.id.player_background_img);   // 背景图片

        mLoveBtn = this.findViewById(R.id.player_love_btn);
        mDownloadBtn = this.findViewById(R.id.player_download_btn);

        mPlayMusicView = this.findViewById(R.id.play_music_view);               // 旋转光盘部分


        mPlayMusicView.setMusicIcon("");


        // 创建对象

        // 用于弹出音乐列表的对象
        mSobPopWindow = SobPopWindow.getInstance();

    }

    // 场景动画对象的方法
    private void initBgAnimation() {

        // 列表弹出的动画
        // 设置动画值变化的范围
        mEnterBgAnimator = ValueAnimator.ofFloat(1.0f, 0.7f);
        // 变换时间
        mEnterBgAnimator.setDuration(Constants.BG_ANIMATION_DURATION);
        mEnterBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                // LogUtil.d(TAG, "value -->" + valueAnimator.getAnimatedValue());
                // 获取动画模块计算出了当前alpha值
                float value = (float) valueAnimator.getAnimatedValue();
                // 跟新UI
                updateBgAlpha(value);
            }
        });

        // 列表退出的动画
        mOutBgAnimator = ValueAnimator.ofFloat(0.7f, 1.0f);
        mOutBgAnimator.setDuration(Constants.BG_ANIMATION_DURATION);
        mOutBgAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                // LogUtil.d(TAG, "value -->" + valueAnimator.getAnimatedValue());
                // 获取动画模块计算出了当前alpha值
                float value = (float) valueAnimator.getAnimatedValue();
                // 跟新UI
                updateBgAlpha(value);
            }
        });


    }


    private void initView() {

        // 初始界面
        if (!TextUtils.isEmpty(mTrackTitleText)) {
            mTrackTitle.setText(mTrackTitleText);
        }


        // 创建适配器
        mTrackPagerAdapter = new PlayerTrackPagerAdapter();
        // 设置适配器
        mTrackPageView.setAdapter(mTrackPagerAdapter);


        mSobPopWindow.registerViewCallback(this);

        if (mCurrentTrack != null) {
            initLoveBtn(mCurrentTrack);
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private void initListener() {

        mLoveBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 添加我喜欢或者删除
                // Toast.makeText(BaseApplication.getAppContext(), "添加我喜欢", Toast.LENGTH_LONG).show();

                if (mLoveSongPresenter != null) {
                    if (mLoveSongPresenter.isLoved(mCurrentTrack)) {
                        mLoveSongPresenter.delLoveSong(mCurrentTrack);
                    } else {
                        mLoveSongPresenter.addLoveSong(mCurrentTrack);
                    }
                }
            }
        });

        mDownloadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 下载音乐
                // Toast.makeText(BaseApplication.getAppContext(), "下载功能", Toast.LENGTH_LONG).show();

            }
        });

        // 播放暂停键的事件
        mControlBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 如果现在是播放状态 就暂停播放 ，
                if (mPlayerPresenter.isPlaying()) {
                    mPlayerPresenter.pause();
                } else {
                    // 否则开始播放
                    mPlayerPresenter.play();
                }
            }
        });

        // 进度条的事件
        mDurationBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean isFormUser) {
                if (isFormUser) {
                    mCurrentProgress = progress;
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                mIsUserTouchProgressBar = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mIsUserTouchProgressBar = false;
                // 手离开拖到进度是更新
                mPlayerPresenter.seekTo(mCurrentProgress);
            }
        });

        // 上一首事件
        mPlayPreBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 播放上一首
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playPre();
                }
            }
        });

        // 下一首事件
        mPlayNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 播放下一首
                if (mPlayerPresenter != null) {
                    mPlayerPresenter.playNext();
                }
            }
        });

        mTrackPageView.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {


                LogUtil.d(TAG, "position -->" + position);

                // 当页面选中的时候，就去切换播放的内容
                if (mPlayerPresenter != null && mIsUserSlidePager) {
                    mPlayerPresenter.playByIndex(position);
                }

                mIsUserSlidePager = false;

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        // 拖动图片的事件
        mTrackPageView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {

                int action = motionEvent.getAction();

                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        mIsUserSlidePager = true;
                        break;
                    case MotionEvent.ACTION_BUTTON_PRESS:
                    default:
                        break;
                }
                return false;
            }
        });

        // 播放模式的切换事件
        mPlayModeSwitchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchPlayMode();
            }
        });

        // 显示播放列表的按钮
        mPlayListBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 显示播放列表

                // 显示在底部

                if (mSobPopWindow.isReady) {

                    if (mSobPopWindow.isShowing()) {
                        mSobPopWindow.dismiss();
                    }

                    mSobPopWindow.showAtLocation(view, Gravity.BOTTOM, 0, 0);

                    // 修改背景的透明度有一个渐变的过程
                    mEnterBgAnimator.start();
                }
            }
        });

    }

    private void switchPlayMode() {
        if (mPlayerPresenter != null) {
            // 根据当前播放模式获取下一个播放模式
            XmPlayListControl.PlayMode playMode = sPlayModeRule.get(mCurrentMode);
            // 通知底层改变播放模式
            mPlayerPresenter.switchPlayMode(playMode);
        }
    }

    public void updateBgAlpha(float alpha) {
        // 得到当前窗口
        Window window = this.getWindow();
        // 获取到窗口的属性
        WindowManager.LayoutParams attributes = window.getAttributes();
        // 修改属性
        attributes.alpha = alpha;
        // 刷新窗口的属性
        window.setAttributes(attributes);
    }

    /**
     * 更据当前的播放模式跟新UI
     * 更据当前的播放模式跟新UI
     */
    private void updatePlayModeBtnImg() {
        int resId = R.drawable.selector_play_mode_list;

        switch (mCurrentMode) {
            case PLAY_MODEL_LIST:
                resId = R.drawable.selector_play_mode_list;
                break;
            case PLAY_MODEL_RANDOM:
                resId = R.drawable.selector_play_mode_random;
                break;
            case PLAY_MODEL_SINGLE_LOOP:
                resId = R.drawable.selector_play_mode_loop;
                break;
            case PLAY_MODEL_LIST_LOOP:
                resId = R.drawable.selector_play_mode_loop_list;
                break;
            default:
                LogUtil.d(TAG, "Some logic wrong");
                break;
        }
        mPlayModeSwitchBtn.setImageResource(resId);
    }


    @Override
    public void onPlayStart() {
        // 开始播放， 修改UI成暂停的按钮
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.stop_music);
        }

        mPlayMusicView.StartPlay();
    }

    @Override
    public void onPlayPause() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.play_music);
        }

        mPlayMusicView.StopPlay();
    }

    @Override
    public void onPlayStop() {
        if (mControlBtn != null) {
            mControlBtn.setImageResource(R.mipmap.play_music);
        }
        mPlayMusicView.StopPlay();
    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void nextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> list) {
        // LogUtil.d(TAG, "list -->" + list);
        // 把数据设置到适配器里
        if (mTrackPagerAdapter != null) {
            mTrackPagerAdapter.setData(list);
        }
    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {

        // 跟新播放模式成功的回调
        mCurrentMode = playMode;
        updatePlayModeBtnImg();

    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onProgressChange(int currentDuration, int total) {

        String totalDuration;
        String currentPosition;
        //1. 全部的时长
        if (total > 1000 * 60 * 60) {
            totalDuration = mHourFormat.format(total);
            currentPosition = mHourFormat.format(currentDuration);
        } else {
            totalDuration = mMinFormat.format(total);
            currentPosition = mMinFormat.format(currentDuration);
        }

        if (mTotalDuration != null) {
            mTotalDuration.setText(totalDuration);
        }

        //2. 更新当前时间
        if (mCurrentPosition != null) {
            mCurrentPosition.setText(currentPosition);
        }

        //3. 更新进度条

        // 设置进度条的最大值
        mDurationBar.setMax(total);

        // 更新
        if (!mIsUserTouchProgressBar) {
            mDurationBar.setProgress(currentDuration);
        }
    }

    @Override
    public void onTrackUpdate(Track track, int playIndex) {

        mCurrentTrack = track;

        if (track == null) {
            LogUtil.d(TAG, "onTrackUpdate --> track is null");

            return;
        }

        this.mTrackTitleText = track.getTrackTitle();

        if (mTrackTitle != null) {
            // 设置当前界面的标题
            mTrackTitle.setText(mTrackTitleText);
        }

        // 当节目改变的时候，我们就获取到当前播放中播放位置
        // 当前的节目改变以后，要修改页面的照片
        if (mTrackPageView != null) {
            mTrackPageView.setCurrentItem(playIndex, true);
        }

        // 设置背景图片
        final String coverUrlLarge = track.getCoverUrlLarge();

        if (!TextUtils.isEmpty(coverUrlLarge)) {
            Picasso.with(mContext).load(coverUrlLarge).into(mPlayerBackgroundImg, new Callback() {
                @Override
                public void onSuccess() {
                    ImageBlur.makeBlur(mPlayerBackgroundImg, mContext);
                }

                @Override
                public void onError() {
                    mPlayerBackgroundImg.setImageResource(R.mipmap.player_background_img);
                }
            });
        } else {
            mPlayerBackgroundImg.setImageResource(R.mipmap.player_background_img);
        }

        mPlayMusicView.setMusicIcon(coverUrlLarge);

        initLoveBtn(mCurrentTrack);
    }

    private void initLoveBtn(Track track) {
        // 判断是否该歌曲点了我喜欢
        if (mLoveSongPresenter != null) {
            if (mLoveSongPresenter.isLoved(track)) {
                mLoveBtn.setImageResource(R.mipmap.loved_normal);
            } else {
                mLoveBtn.setImageResource(R.mipmap.love_normal);
            }
        }
    }

    @Override
    public void updateListOrder(boolean isReverse) {

    }


    @Override
    public void SobPopOpen() {

    }

    @Override
    public void SobPopClose() {
        mOutBgAnimator.start();
    }

    @Override
    public void onLoveSongAdd(boolean isSuccess) {

    }

    @Override
    public void onLoveSongDel(boolean isSuccess) {

    }

    @Override
    public void onLoveSongLoaded(List<Track> tracks) {
        for (Track track : tracks) {
            if (track.getDataId() == mCurrentTrack.getDataId()) {
                mLoveBtn.setImageResource(R.mipmap.loved_normal);

                return;
            }
        }

        mLoveBtn.setImageResource(R.mipmap.love_normal);
    }

    @Override
    public void onLoveSongClean(boolean isSuccess) {

    }

    @Override
    public void onLoveSongFull() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unRegisterViewCallback(this);
            mPlayerPresenter = null;
        }

        if (mSobPopWindow != null) {
            mSobPopWindow.unRegisterViewCallback(this);
            mSobPopWindow = null;
        }

        if (mLoveSongPresenter != null) {
            mLoveSongPresenter.unRegisterViewCallback(this);
        }

    }
}
